import React, { Component } from 'react';
import {
    View, Text, ScrollView, Image, ImageBackground,
    RefreshControl, Modal, TouchableOpacity, Alert
} from 'react-native';
import Redux, { connect } from 'react-redux';
import Toast from 'react-native-easy-toast';
import CInput from 'react-native-controlled-input';

import { TABBAR_LABEL, ROUTERMAP, Global, AVALIABLE_COIN_TYPES, API_MAP, TOAST_MESSAGE } from '../util/constants';
import BalanceItem from '../components/BalanceItem';
import { scaleSize, scaleFontSize } from '../util/size';
import icons from '../util/icons';
import * as balanceAction from '../actions/balance';
import * as exchangeBalanceAction from '../actions/exchangeBalance';
import { IReduxUserInfo, IReduxMarketInfo } from '../interface';
import { utilTotalBalanceAmountToBTC } from '../util/balanceUtil';
import { utilGetAmountToByCoinType } from '../util/marketUtil';
import { request } from '../util';
import NccButton from '../components/Button';
import { utilTransferInputValue } from '../util/util';
import Constants from '../service/constants';

interface IProps {
    balance: any,
    navigation: any,
    updateBalanceInfo: Redux.Action,
    user: IReduxUserInfo,
    market: IReduxMarketInfo,
    updateExchangeBalanceInfo: exchangeBalanceAction.IFuncUpdateExchangeBalanceInfo,
}

interface IState{
    refreshing: boolean,
    lastRefreshTime: number,
    modalVisible: boolean,
    coinTypeToExchange: string,
    bankToExchangeAmount: string,
    bankToExchangeCoinType: string,
    bankToExchangeButtonState: string,
}

const BANK_TO_EXCHANGE_BUTTON_STATE = {
    loading: '转账中...',
    onready: '确定',
}

const REFRESH_MS = 10000; // 刷新频率

class BalanceView extends Component<IProps, IState> {
    constructor(props) {
        super(props);
        this.state ={
            refreshing: false,
            lastRefreshTime: Date.now() - REFRESH_MS,
            modalVisible: false,
            coinTypeToExchange: '',
            bankToExchangeAmount: '',
            bankToExchangeCoinType: '',
            bankToExchangeButtonState: BANK_TO_EXCHANGE_BUTTON_STATE.onready,
        }
    }

    static navigationOptions = {
        tabBarLabel: TABBAR_LABEL.balance,
        tabBarIcon: ({ focused }) => {
            if (focused) {
                return (
                    <Image source={icons.tabBalanceO} style={Global.tabIconStyles}/>
                );
            }
            return (
                <Image source={icons.tabBalance} style={Global.tabIconStyles}/>
            );
        },
    };

    componentDidMount() {
        this.loadBalanceInfo();
        Constants.getBalanceSymbolList().then(res => {
            console.log('getBalanceSymbolList???..', res);
        }).catch(err => {
            console.error('getBalanceSymbolList..', err);
        })
    }

    componentWillUnmount() {
        this.resetBankToExchangeState();
    }

    toast = (content: string) => {
        this.refs.toast.show(content);
    }

    turnToPage = (pageName: string, params?: Object) => {
        this.props.navigation.navigate(pageName, params);
    }

    turnToBalanceItem = (params, data) => {
        let {name} = this.props.user;
        // this.turnToPage(ROUTERMAP.balanceInfo, params);
        // return;
        if (name) {
            this.turnToPage(ROUTERMAP.balanceInfo, params);
        } else {
            this.turnToPage(ROUTERMAP.login, {delUser: true});
        }
    }

    onRefresh = () => {
        // return
        console.log('onrefresh', this.state.lastRefreshTime, Date.now());
        if (this.state.lastRefreshTime + REFRESH_MS > Date.now()) {
            this.toast(TOAST_MESSAGE.REFRESH_TO_MANY_TIMES);
            return;
        }
        this.setState({refreshing: true, lastRefreshTime: Date.now()})
        this.loadBalanceInfo();
    }


    loadBalanceInfo = () => {
        request(API_MAP.balanceBank, {
            method: 'POST',
            data: {}
        }, false,  (err, res) => {
            console.log('onRefresh ,res ...', res);
            this.setState({refreshing: false});
            if (res.retCode == '00') {
                this.props.updateBalanceInfo(res.data);
            }
        })
    }

    loadExchangeBalanceInfo = () => {
        request(API_MAP.balance, {
            method: 'POST',
            data: {
                bankName: 'exchange1',
            }
        }, false,  (err, res) => {
            console.log('onRefresh ,res ...', res);
            this.setState({refreshing: false});
            if (res.retCode == '00') {
                this.props.updateExchangeBalanceInfo(res.data);
            }
        })
    }

    renderData = () => {
        let balanceInfo = this.props.balance;
        let market = this.props.market;
        let coinTypes = AVALIABLE_COIN_TYPES;
        let coinData:any = [];

        Object.keys(coinTypes).forEach((v, index) => {
            let type = coinTypes[v];
            let locked = balanceInfo[`${type}Locked`] || 0;
            let available = balanceInfo[`${type}`] || 0;
            let amountTo = utilGetAmountToByCoinType(market, type);
            amountTo = Number((available * amountTo).toFixed(4));
            coinData.push({
                type,
                available,
                locked,
                amountTo
            });
        })

        return (
            <View style={{
                display: 'flex',
                alignItems: 'center',
                marginTop: - scaleSize(24),
            }}>
                <View>
                    {
                        coinData.map((d, index) => {
                            return (
                                <BalanceItem {...d} key={`one-${index}`} topRightText={'转到交易所'} topRightTextOnPress={() => {
                                    this.comfirmBankToExchange(d.type);
                                }} 
                                onPress={() => this.turnToBalanceItem({
                                    type: d.type,
                                    available: d. available
                                }, d)} />
                            )
                        })
                    }
                </View>
            </View>
        )
    }

    resetBankToExchangeState = () => {
        this.setState({bankToExchangeAmount: '', bankToExchangeCoinType: '', modalVisible: false});
    }

    onChangeBankToExchangeAmount = (value) => {
        value = utilTransferInputValue(value, 'amount');
        this.setState({ bankToExchangeAmount: value });
        return value;
    }

    handleBankToExchange = () => {
        const { bankToExchangeAmount, bankToExchangeCoinType, bankToExchangeButtonState } = this.state;

        if (bankToExchangeButtonState == BANK_TO_EXCHANGE_BUTTON_STATE.loading) {
            return;
        }

        const {balance} = this.props;

        if (!bankToExchangeAmount) {
            return Alert.alert(TOAST_MESSAGE.INVALID_AMOUNT);
        }

        if (!balance[bankToExchangeCoinType] || Number(bankToExchangeAmount) > balance[bankToExchangeCoinType]) {
            return Alert.alert(TOAST_MESSAGE.BALANCE_NOT_ENOUGH);
        }

        this.setState({bankToExchangeButtonState: BANK_TO_EXCHANGE_BUTTON_STATE.loading});

        request(API_MAP.bankToExchange, {
            method: 'POST',
            data: {
                amount: Number(bankToExchangeAmount),
                coinType: bankToExchangeCoinType,
            }
        }, false, (err, res) => {
            if (res.retCode == '00') {
                this.loadBalanceInfo();
                setTimeout(this.loadExchangeBalanceInfo, 1000);
                this.toast(TOAST_MESSAGE.SUCCESS);
                this.setState({bankToExchangeButtonState: BANK_TO_EXCHANGE_BUTTON_STATE.onready});
            } else {
                this.toast(TOAST_MESSAGE.AGAIN_LATER);
            }
            this.resetBankToExchangeState();
        })
    }

    comfirmBankToExchange = (coinType: string) => {
        const {user} = this.props;
        console.log('user...', user);
        if (user && user.name) {
            this.setState({ modalVisible: true, bankToExchangeCoinType: coinType });
        } else {
            this.turnToPage(ROUTERMAP.login, {delUser: true});
        }
    }

    render() {
        let {market, balance} = this.props;
        let balanceAmountToBTC = utilTotalBalanceAmountToBTC(balance, market);
        let amountTo = utilGetAmountToByCoinType(market, 'BTC');
        amountTo = Number((amountTo * balanceAmountToBTC).toFixed(4));
        return (
            <View style={{ display: 'flex', flexDirection: 'column' }}>
                <ScrollView refreshControl={
                    <RefreshControl
                    refreshing={this.state.refreshing}
                    onRefresh={this.onRefresh}
                    />
                }>
                <View style={{ height: scaleSize(250)}}>
                    <ImageBackground source={icons.backgroundBalanceIntfo} style={{height: scaleSize(250)}} resizeMode='cover'>
                    <View style={{ marginTop: 93, marginLeft: scaleSize(36) }}>
                        <Text style={{
                            fontFamily: 'PingFangSC-Medium',
                            fontSize: scaleFontSize(16),
                            color: '#FFFFFF',
                            lineHeight: scaleSize(22),
                        }}>总资产折合(银行钱包) (BTC)</Text>

                        <Text style={{
                            fontFamily: 'Helvetica-Bold',
                            fontSize: scaleFontSize(36),
                            color: '#FFFFFF',
                            lineHeight: scaleSize(43),
                            marginTop: scaleSize(5),
                        }}>
                            {balanceAmountToBTC}
                        </Text>

                        <Text style={{
                            opacity: 0.65,
                            fontFamily: 'Helvetica',
                            fontSize: scaleFontSize(16),
                            color: '#FFFFFF',
                            marginTop: scaleSize(9),
                        }}>
                            ≈ {amountTo} CNY
                        </Text>
                    </View>
                    </ImageBackground>
                </View>
                {
                    this.renderData()
                }
                <Modal
                        visible={this.state.modalVisible}
                        animationType={'none'}
                        transparent={true}
                    >
                        <TouchableOpacity activeOpacity={1} style={{ flex: 1 }} onPress={() => {
                            this.resetBankToExchangeState();
                        }}>
                            <View style={{
                                display: 'flex',
                                flex: 1,
                                backgroundColor: 'rgba(0,0,0,0.5)'
                            }}>
                                <View style={{
                                    alignSelf: 'center',
                                    marginTop: scaleSize(180),
                                    height: 300,
                                    width: '100%',
                                    backgroundColor: 'white',
                                    justifyContent: 'center',
                                    padding: scaleSize(20),
                                }}>
                                    <Text>转到交易所</Text>
                                    <View style={{
                                        display: 'flex',
                                        flexDirection: 'row',
                                        justifyContent: 'space-between',
                                        marginTop: scaleSize(17),
                                    }}>
                                        <CInput style={[
                                            {
                                                borderWidth: 1,
                                                width: scaleSize(260),
                                                height: scaleSize(40),
                                                borderColor: Global.grayColor,
                                                paddingLeft: scaleSize(5),
                                            }
                                        ]}
                                        keyboardType={'numeric'}
                                        underlineColorAndroid={'transparent'}
                                        onChangeText={this.onChangeBankToExchangeAmount}
                                        value={this.state.bankToExchangeAmount}
                                        ></CInput>
                                        <Text style={{
                                            lineHeight: scaleSize(40),
                                        }}>{this.state.bankToExchangeCoinType}</Text>
                                    </View>
                                    <View style={{
                                        marginTop: scaleSize(30),
                                    }}>
                                        <NccButton text={this.state.bankToExchangeButtonState} onPress={this.handleBankToExchange} buttonStyle={{
                                            // width: scaleSize(200),
                                        }}/>
                                    </View>
                                </View>
                            </View>
                        </TouchableOpacity>
                    </Modal>
                </ScrollView>
                <Toast ref='toast' position={'center'} />
            </View>
        )
    }
}

export default connect(
    (state) => ({
        balance: state.balance,
        user: state.user,
        market: state.market,
    }),
    (dispatch) => ({
        updateBalanceInfo: (data) => dispatch(balanceAction.updateBalanceInfo(data)),
        updateExchangeBalanceInfo: (data) => dispatch(exchangeBalanceAction.updateBalanceInfo(data)),
    })
)(BalanceView);

// xy32351993